package ar.edu.itba.it.paw.web;

import java.util.Date;

import org.apache.wicket.Request;
import org.apache.wicket.Session;
import org.apache.wicket.injection.web.InjectorHolder;
import org.apache.wicket.protocol.http.WebSession;
import org.apache.wicket.spring.injection.annot.SpringBean;

import ar.edu.itba.it.paw.domain.User;
import ar.edu.itba.it.paw.repo.UserRepo;


public class MercadoLibreSession extends WebSession {

	@SpringBean
	UserRepo userRepo;
	
	private Integer userId;

	public static MercadoLibreSession get() {
		return (MercadoLibreSession) Session.get();
	}

	public MercadoLibreSession(Request request) {
		super(request);
		InjectorHolder.getInjector().inject(this);
	}

	public User getUser() {
		if (isSignedIn()){
			return userRepo.getUser(userId);
		}
		return null;
	}

	public boolean signIn(String username, String password) {
		User user = userRepo.getUser(username);
		if (user != null && user.checkPassword(password)) {
			this.userId = user.getId();
			user.setLast_login(new Date());
			return true;
		}
		return false;
	}

	public boolean isSignedIn() {
		return userId != null;
	}

	public void signOut() {
        Session.get().invalidate();
        clear();
	}
}
